import json
import re
import pdfplumber
import utils 

def extract_json_from_pdf(pdf_path):
    # Initialize the result structure
    result = {
        "title": "企业战略管理",
        "chapters": []
    } 
    # Split the text into lines and process
    with pdfplumber.open(pdf_path) as pdf:
        current_chapter = None
        current_section = None
        current_subsection = None
        for page in pdf.pages:
            lines = page.extract_text_lines()
            for rawLine in lines: 
                line = rawLine['text']
                line = re.sub(r'(?<=[\u4e00-\u9fff])\s+(?=[\u4e00-\u9fff])', '', line).replace('•', '')
                line = line.strip()
                chapter_match = re.match(r'第([一二三四五六七八九十]+)章\s*(.+)', line)
                if chapter_match:
                    chapter_number = utils.chinese_to_arabic(chapter_match.group(1))
                    chapter_title = line #chapter_match.group(2)
                    current_chapter = {
                        "chapter_number": chapter_number,
                        "title": chapter_title,
                        "content": "" ,
                        "sections": []
                    }
                    result["chapters"].append(current_chapter)
                    current_section = None
                    current_subsection = None
                    continue
                
                # Match section (e.g., "第一节 古典管理理论")
                section_match = re.match(r'第([一二三四五六七八九十]+)节\s*(.+)', line)
                if section_match and current_chapter:
                    section_number = utils.chinese_to_arabic(section_match.group(1))
                    section_number = f"{current_chapter['chapter_number']}.{section_number}"
                    section_title = line #section_match.group(2)
                    current_section = {
                        "section_number": section_number,
                        "title": section_title,
                        "content": "" ,
                        "subsections": []
                    }
                    current_chapter["sections"].append(current_section)
                    current_subsection = None
                    continue
                    
                # Match subsection (e.g., "一、早期的管理思想")
                subsection_match = re.match(r'([—一二三四五六七八九十]+)、(.+)', line)
                current_section_number = 0
                if not subsection_match and current_section:
                    chars = rawLine['chars']
                    charSize = chars[0]['size']
                    if charSize == 9.5 and len(re.findall(r'[\u4e00-\u9fff]', line)) >= 2 and rawLine['x1'] < 320 and rawLine['x0'] > 60 \
                        and not re.match(r'^\(', line) and not re.match(r'^\d', line) and len(line) < 17:
                        current_section_number = len(current_section["subsections"]) + 1
                if subsection_match and current_section:
                    current_section_number = utils.chinese_to_arabic(subsection_match.group(1))
                    if current_section_number is None:
                        current_section_number = len(current_section["subsections"]) + 1
                if current_section_number > 0:
                    subsection_number = f"{current_section['section_number']}.{current_section_number}"
                    subsection_title = line #subsection_match.group(2)
                    current_subsection = {
                        "subsection_number": subsection_number,
                        "title": subsection_title,
                        "content": "" 
                    }
                    current_section["subsections"].append(current_subsection)
                    continue
                    
                if line and not (chapter_match or section_match or subsection_match):
                    if current_chapter and not (current_section or current_subsection):
                        current_chapter["content"] += line
                    if current_section and not current_subsection:
                        current_section["content"] += line
                    if current_subsection:
                        current_subsection["content"] += line
                     
    return result



# Path to your PDF file
pdf_path = "/Users/martinzhang/mt-20230221/zxjd-proj-20240405/04-development/smart-learn-go/textbook_expert/resources/02-企业战略管理.pdf"


# Parse the text and create JSON
json_data = extract_json_from_pdf(pdf_path)

# Save to a JSON file
with open('company_strategy.json', 'w', encoding='utf-8') as json_file:
    json.dump(json_data, json_file, ensure_ascii=False, indent=2)

print("JSON file 'company_strategy.json' has been created.")